package cn.tedu.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCLogin2 {
    public static void main(String[] args) {
        try (Connection connection = DBUtil.getConnection()) {
            String sql1 = "select username from userinfo where username=? ";
            String sql2 = "insert into userinfo (username,password,nickname,age) values (?,?,?,?)";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            PreparedStatement ps2 = connection.prepareStatement(sql2);
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名：");
            String username = scanner.nextLine();
            ps1.setString(1, username);
            if (ps1.executeQuery().next()) {
                System.out.println("用户名已存在");
            } else {
                System.out.println("请输入密码：");
                String password = scanner.nextLine();
                System.out.println("请输入昵称：");
                String nickname = scanner.nextLine();
                System.out.println("请输入年龄：");
                int age = scanner.nextInt();
                ps2.setString(1, username);
                ps2.setString(2, password);
                ps2.setString(3, nickname);
                ps2.setInt(4, age);
                if (ps2.executeUpdate() > 0) {
                    System.out.println("注册成功");
                } else {
                    System.out.println("注册失败");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
